import {
  IPublicTypeAppConfig,
  IPublicTypeAssetsJson,
  IPublicTypeConfigure,
  IPublicTypeFieldConfig,
  IPublicTypeComponentMetadata,
  IPublicTypePackage,
  IPublicTypeRootSchema,
} from '@alilc/lowcode-types';
import { ITypeEntity, ITypeEntityField } from '../../superType/types';
import { LcProjectMember, MembeRole } from './auth.type';
import { LcProjectEnvInfo } from './env.type';
import {
  IPublicTypeUtilItem,
  LcLowcodePlugin,
  LcProjectAsset,
  LcProjectModule,
  LcProjectStoreInfo,
} from './asset.type';
// import { LceMetaProp } from '@/components/superType/MetaForm/ParamsSetter';
import { HistoryType } from '../server/history/HistoryType';
import { AppthenCanvas } from './canvas.type';

export interface IDocConfigure extends IPublicTypeConfigure {
  props: any[];
}

export type DocFrameType = 'web' | 'app';
export type DocClientType = 'web' | 'weapp' | 'h5' | 'app';

export class LcProject {
  _id?: string;
  /** 项目版本号 */
  version?: number;
  /** 项目哈希值 */
  path?: string;
  hash?: string;
  type?: DocFrameType;
  theme?: string;
  title?: string;
  icon?: string;
  description?: string;
  screenshot?:
    | string
    | {
        url: string;
        w: number;
        h: number;
      };
  frames?: DocFrameType[];
  clients?: DocClientType[];
  /**
   * 文件夹
   * [预置] global 全局组件
   * 自定义文件夹名
   */
  folder?: string;
  width?: number;
  height?: number;
  schema?: any;

  cssHash?: string;
  cssPath?: string;
  cssUpdateAt?: number;

  packages?: Record<DocFrameType, IPublicTypePackage[]> | IPublicTypePackage[];
  documents?: Partial<LcDocument>[];

  envInfo?: LcProjectEnvInfo;

  appConfig?: LcProjectAppConfig;

  storeInfo?: LcProjectStoreInfo;

  /**
   * 插件信息
   * @deprecated 不单独存储插件安装情况，安装模块表示安装所有插件，配置信息也将存储于模块
   */
  plugins?: LcProjectPlugin[];

  /**
   * 主题信息
   * 支持多主题配置，每个主题包含 Antd tokens、CSS 变量和 Tailwind 配置
   * {
   *   "default": {
   *     "name": "默认主题",
   *     "antdTokens": { "colorPrimary": "#1677ff" },
   *     "cssVariables": { "--color-primary": "#1677ff" },
   *     "tailwindConfig": { "colors": { "primary": "#1677ff" } }
   *   }
   * }
   */
  themes?: Record<string, any>;

  /**
   * 当前激活的主题 key
   */
  activeTheme?: string;

  /**
   * 画板
   */
  canvas?: AppthenCanvas;

  /**
   * 资产包信息
   */
  assets?: LcProjectAsset[];

  /**
   * 模块引用信息
   */
  modules?: LcProjectModule[];

  /**
   * 安装场景记录
   */
  scenes?: LcProjectScene[];

  /**
   * 资源链接信息
   */
  links?: LcProjectLink[];

  /**
   * 是否模板项目 0/1
   */
  isTemplate?: number;
  /**
   * 模板分类标签
   */
  templateTags?: string[];

  /**
   * 主组件库
   */
  mainComponent?: string;

  deleteAt?: number;
  deleteBy?: number;

  followUserIds?: number[];

  member?: LcProjectMember[];
  // 根据TeamId&Member计算得来
  canEdit?: boolean;

  isPublic?: boolean;
  allowCopy?: boolean;
  allowCopyRole?: MembeRole;

  // 🆕 公开访问配置
  publicIdentifier?: string; // 系统生成的唯一标识符
  publicEnabledAt?: number; // 公开访问启用时间
  publicEnabledBy?: number; // 启用者

  // 🆕 自定义域名配置
  customDomain?: {
    /** 绑定的自定义域名 */
    domain: string;
    /** 域名状态 */
    status: 'pending' | 'active' | 'error' | 'disabled';
    /** DNS 配置状态 */
    dnsStatus: {
      cnameValid: boolean;
      lastChecked: number;
      error?: string;
    };
    /** SSL 证书配置 */
    ssl: {
      status: 'none' | 'pending' | 'active' | 'expired' | 'error';
      issuer?: string;
      expiresAt?: number;
      autoRenew: boolean;
    };
    /** 配置时间 */
    createdAt: number;
    updatedAt: number;
    createdBy: number;
    /** 强制 HTTPS */
    forceHttps: boolean;
  };

  lastUpdateBy?: number;

  teamId?: number;
  userId?: number;
  create_time?: number;
  update_time?: number;

  schemaPartial?: Partial<any>;
}

export interface LcProjectLink {
  title: string;
  path: string;
  targetProjectId: string;
  targetProjectName?: string;
  targetPath?: string;
  syncAt?: number;
  syncBy?: number;
  syncStatus?: 'pending' | 'success' | 'failed';
  syncError?: string;

  /**
   * 是否来自模块自动安装
   */
  fromModuleId?: string;
}

export interface LcProjectAppConfig {
  /**
   * 项目首页
   */
  indexPage?: string;

  reactVersion?: string;

  /**
   * 其他字段参考小程序文档
   */
  [propName: string]: any;
}

export class LcProjectPlugin {
  pluginName: string;
  moduleId?: string;
  lowcodePlugin?: LcLowcodePlugin;
  /**
   * @deprecated
   */
  version?: string;
  /**
   * @deprecated
   */
  config?: Record<string, any>;
}

export class LcProjectScene {
  sceneId: string;
  installAt?: number;
  installBy?: number;
  updateAt?: number;
}

export class LcDocument {
  _id?: string;
  type?: keyof typeof LcDocumentType;
  frames?: DocFrameType[];
  clients?: DocClientType[];
  /** 文档版本号 */
  version?: number;
  /** 文档哈希值 */
  hash?: string;
  /* 文件系统路径 */
  path?: string;
  /**
   * 穿梭组件
   */
  portal?: boolean;
  /**
   * 存档（不发布到项目中）
   */
  onlySave?: boolean;
  projectId: string;
  title: string;
  description?: string;
  poster?: string;
  screenshot?:
    | string
    | {
        url: string;
        w: number;
        h: number;
      };
  icon?: string;
  /**
   * 项目内唯一
   */
  fileName: string;
  route?: {
    path?: string;
    name?: string;
    redirect?: string;
    index?: boolean;
    order?: number;
    /**
     * 用作嵌套路由的Layout
     */
    layout?: boolean;
    /**
     * 不被Layout包裹
     */
    noLayout?: boolean;
    children?: string[];
  };
  schema?: IPublicTypeRootSchema;

  /**
   * @deprecated
   */
  packages?: Record<string, any>[];

  assets?: LcProjectAsset[];
  componentsMap?: LcDocumentComponentsMapItem[];
  componentsRoot?: Record<DocFrameType, LcDocumentComponentsMapItem[]>;
  utilsMap?: IPublicTypeUtilItem[];
  tags?: string[];

  width?: number;
  height?: number;
  backgroundColor?: string;

  /**
   * 文件夹
   * [预置] global 全局组件
   * 自定义文件夹名
   */
  folder?: string;

  /**
   * 文件夹路径
   * 完整的文件夹路径，用于层级结构
   */
  folderPath?: string;

  /**
   * @deprecated
   */
  configure?: IDocConfigure;
  componentMeta?: IPublicTypeComponentMetadata;

  pageConfig?: LcDocumentMiniPageConfig;

  /**
   * CSS 内容的哈希值
   * 用于变更检测和缓存优化
   */
  cssHash?: string;
  cssPath?: string;

  /* css 更新时间 */
  cssUpdateAt?: number;

  /* 区块关联 */
  from?: {
    projectId?: string;
    documentId?: string;
    sceneId?: string;
    fileName?: string;
    nodeId?: string;
  };

  /**
   * 版本分支（暂时用于文件重名，编辑态只加载空或master，后期实现分支功能，可用于其他）
   * master 默认主分支
   * share 用于分享模式
   */
  branch?: string;

  share?: boolean;
  scene?: string;
  childScene?: string;
  trade?: string;
  childTrade?: string;

  types?: ITypeEntity[];

  teamId?: number;
  userId?: number;
  lastUpdateBy?: number;

  create_time?: number;
  update_time?: number;
}

export interface LcDocumentMiniPageConfig {
  /**
   * 导航栏背景颜色，如 #000000
   */
  navigationBarBackgroundColor?: string;
  /**
   * 导航栏标题颜色，仅支持 black / white
   */
  navigationBarTextStyle?: string;
  /**
   * 导航栏标题文字内容
   */
  navigationBarTitleText?: string;
  /**
   * 导航栏样式，仅支持以下值：
   * default 默认样式
   * custom 自定义导航栏，只保留右上角胶囊按钮
   */
  navigationStyle?: string;
  /**
   * 窗口的背景色
   */
  backgroundColor?: string;
  /**
   * 下拉 loading 的样式，仅支持 dark / light
   */
  backgroundTextStyle?: string;
}

export const LcDocumentType = {
  Page: 'Page',
  Component: 'Component',
  Block: 'Block',
};

export interface LcDocumentUtilsMapItem {
  package?: string;
  version?: string;
  exportName?: string;
  main?: string;
  destructuring?: boolean;
  subName?: string;
  componentName: string;
  devMode?: string;
}

export interface LcDocumentComponentsMapItem {
  package?: string;
  version?: string;
  exportName?: string;
  main?: string;
  destructuring?: boolean;
  subName?: string;
  componentName: string;
  devMode?: string;
}

export class LcDocumentBackup {
  _id?: string;
  data?: LcDocument;
  docId?: string;
  projectId?: string;
  type?: HistoryType;
  teamId?: number;
  userId?: number;
  createAt?: number;
}

export class LcModule {
  config: {
    // 自动插入项目中的物料元素清单
  };

  version: '';
  versionNumber: number;

  /**
   * 推荐标签
   */
  tags?: string[];

  /**
   * 全局常量
   */
  constants: Record<string, any>;

  /**
   * 样式集
   */
  styles: [];

  /**
   * 全局动作
   */
  utils: [];

  /**
   * 区块
   */
  blocks: LcDocument[];

  /**
   * 自定义组件
   */
  components: LcDocument[];

  /**
   * 模板
   */
  pages: LcDocument[];

  /**
   * 模型
   */
  types: ITypeEntity[];
}
